
<template >
<div class="foreigntradecontract">

  <div class="head">
    <h2>外贸合同</h2>
    <div class="head-ctrl">
      <div class="order-number">
        {{businessformNO}}
      </div>
      <!-- <el-button type="primary">导出</el-button> -->
    </div>
  </div>

  <div class="head-1">
    <p style="font-weight:bolder;"> TIAN JIN FINANCIAL TRADE LINK IMPORT AND EXPORT CO.,LTD</p>
    <p>NO.88-2-2205,HUANHE SOUTH ROAD,CHINA(TIANJIN)PILOT FREE TRADE ZONE</p>
    <p>TIANJIN AIRPORT ECONOMIC AREA),TIANJIN,CHINA"</p>
  </div>

  <div class="contract">
    <h1>销售合同SALES CONTRACT</h1>
    <div class="clearfix">
      <div class="contract-order">
        <el-form label-width="80px">
          <el-form-item label="编号NO:">
            <el-input placeholder="请输入相关内容" :readonly="!editable" v-model="data.bf_orderNumber"></el-input>
          </el-form-item>

          <el-form-item label="日期Date:">
            <el-date-picker  value-format="yyyy-MM-dd" :readonly="!editable" @change="mustUpdate2" v-model="bf_orderDate"></el-date-picker>
          </el-form-item>

        </el-form>
      </div>
    </div>

    <div class="contract-1">
      <el-form label-width="120px">
        <el-form-item label="买方BUYER:">
          <el-select :disabled="!editable" @change="selBuyer" v-model="data.bf_buy_name">
            <el-option v-for="(item, index) in bf_buy_nameOptions" :key="index" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="地址ADDRESS:">
          <el-input placeholder="请输入相关内容" :readonly="!editable" v-model="data.bf_buy_address"></el-input>
        </el-form-item>
      </el-form>


      <el-form :inline="true">
        <el-form-item label="电话TEL:">
          <el-input placeholder="请输入相关内容" :readonly="!editable" v-model="data.bf_buy_tel"></el-input>
        </el-form-item>
        <el-form-item label="传真FAX:">
          <el-input placeholder="请输入相关内容" :readonly="!editable" v-model="data.bf_buy_fax"></el-input>
        </el-form-item>

        <el-form-item label="邮箱Email:">
          <el-input placeholder="请输入相关内容" :readonly="!editable" v-model="data.bf_buy_email"></el-input>
        </el-form-item>
      </el-form>

      <div>
        <p><span>卖方SELLER:</span>天津金贸链进出口有限公司</p>
        <p>TIAN JIN FINANCIAL TRADE LINK IMPORT AND EXPORT CO.,LTD</p>
        <p><span>地址ADDERSS:</span>天津自贸试验区（空港经济区）环河南路88号2-2205号</p>
        <p>NO.88-2-2205,HUANHE SOUTH ROAD,CHINA(TIANJIN)PILOT FREE TRADE ZONE TIANJIN AIRPORT ECONOMIC AREA),TIANJIN,CHINA</p>
        <p><span>电话TEL:</span> 010-50911255 传真FAX: 010-50911288 邮箱EMAIL: </p>
      </div>
    </div>

    <div class="contract-table">
      <div class="contract-table-1">
        <p><span>1、 经买卖双方同意，按照以下条款由买方购进卖方售出以下产品：</span></p>
        The contract is made by and between the buyer and seller; whereby the buyer agrees to buy and the seller agrees to sell the under-mentioned goods subject to the terms and conditions as stipulated hereinafter:
      </div>

      <div class="contract-table-2">
        <el-table :data="tableData" @cell-click="clickEditTableCell"  border style="width: 100%" :span-method="spanMethod">
          <el-table-column label="序号">
            <el-table-column type="index" label="NO" :index="indexMethod"></el-table-column>
          </el-table-column>

          <el-table-column label="产品" min-width="100">
            <el-table-column prop="bf_table1_product" label="DESCRIPTION OF GOODS">
              <template slot-scope="scope">
                <span  class="cell-edit-input">
                  <!-- <el-input placeholder="请输入相关内容"  :readonly="!editable" v-if="!scope.row.bf_table1_summary" v-model="scope.row.bf_table1_product" ></el-input> -->

                  <el-tooltip effect="dark" v-if="!scope.row.bf_table1_summary"  placement="top">
                    <div slot="content">{{scope.row.bf_table1_product || '暂无数据'}}</div>
                  <el-input placeholder="请输入相关内容"  :readonly="!editable" v-model="scope.row.bf_table1_product" ></el-input>
                  </el-tooltip>
                  <div v-else class="placeholder"></div>
                </span>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column label="规格型号" min-width="100">
            <el-table-column prop="bf_table1_description" label="SPECIFICATION MODEL">
              <template slot-scope="scope">
                <span  class="cell-edit-input">
                  <el-tooltip effect="dark" v-if="!scope.row.bf_table1_summary" placement="top">
                    <div slot="content">{{scope.row.bf_table1_description  || '暂无数据'}}</div>
                    <el-input placeholder="请输入相关内容"  :readonly="!editable"  v-model="scope.row.bf_table1_description" ></el-input>
                  </el-tooltip>
                  <div v-else class="placeholder"></div>
                </span>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column label="数量" min-width="100">
            <el-table-column prop="bf_table1_quantity" label="QUANTITY(PCS)">
              <template slot-scope="scope">
                <span  class="cell-edit-input">
                  <el-input-number  :disabled="!editable"  type="number" v-if="scope.row.specialColumn" :controls="false" v-model="scope.row.bf_table1_quantity" :min="0" ></el-input-number>
                  <el-input-number  :disabled="!editable" v-else type="number"  v-model="scope.row.bf_table1_quantity" :controls="false"  @change="handleTableNumberChange" :min="0" ></el-input-number>
                </span>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column label="单价"  min-width="100" :render-header="currencySel('单价')">

            <el-table-column prop="bf_table1_price" label="UNIT PRICE"  :render-header="currentSelEN('UNIT PRICE')">
              <template slot-scope="scope">
                <span  class="cell-edit-input">
                  <el-input-number  :disabled="!editable" v-if="!scope.row.bf_table1_summary" :controls="false" v-model="scope.row.bf_table1_price"  @change="handleTableNumberChange" :min="0" ></el-input-number>
                  <div v-else class="placeholder"></div>
                </span>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column label="金额" min-width="100">
            <el-table-column prop="bf_table1_lineAmount" label="AMOUNT" :render-header="currentSelEN('AMOUNT')">
              <template slot-scope="scope">
                <span  class="cell-edit-input">
                  <el-input v-if="scope.row.specialColumn" placeholder="请输入相关内容"  :readonly="true"   v-model="scope.row.bf_table1_lineAmount" ></el-input>
                  <el-input-number  v-else  :disabled="!editable"   v-model="scope.row.bf_table1_lineAmount" :controls="false" @change="handleTableNumberChange2"  :min="0" ></el-input-number>
                </span>
              </template>
            </el-table-column>
          </el-table-column>


          <el-table-column v-if="editable" label="操作" width="100">
            <template slot-scope="scope">
            <el-button @click="addNewLine(scope.$index, data.bf_table1, $event)" type="text" size="small">添加</el-button>
            <el-button @click="removeCurrentLine(scope.$index, data.bf_table1, $event)" type="text" size="small">移除</el-button>
          </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="extra-table">
          <el-row class="extra-money">
            <el-col :span="8"><div>Deposit定金</div></el-col>
            <el-col :span="8"><div>&nbsp;</div></el-col>
            <el-col :span="8"><input v-model="bf_depositMoney" @input="handleExtraMoney('bf_depositMoney', $event)"/></el-col>
         </el-row>

        <el-row class="extra-money">
            <el-col :span="8"><div>Balance 尾款</div></el-col>
            <el-col :span="8"><div>&nbsp;</div></el-col>
            <el-col :span="8"><div><input v-model="bf_balanceMoney" @input="handleExtraMoney('bf_balanceMoney', $event)"/></div></el-col>
         </el-row>
      </div>

      <div class="special">
        <p><span>2. 原产国Country of Origin：		中国 China</span></p>
        <p><span>3. 成交方式Trade Terms:</span>
          <el-input placeholder="请输入相关内容" :readonly="!editable" v-model="data.bf_tradeTerm"></el-input>
        </p>
        <p><span>4. 包装Packing</span></p>
        <p>标准包装,如果由于不适当的包装而导致的货物损坏和由此产生的费用，卖方应对此负完全的责任。</p>
        <p>To be packed in standard packing. The Sellers shall be liable for any damage of the commodity and expenses incurred on account of improper packing and for any rust attributable to inadequate or improper protective measures taken by the sellers
          in regard to the packing.</p>
        <p><span>5. 唛头Shipping Marks:</span>
          <el-input placeholder="请输入相关内容" :readonly="!editable" v-model="data.bf_shippingMarks"></el-input>
        </p>
        <p><span>6. 交货期DATE OF Delivery</span></p>
        <p>卖方收到定金后60天内交货。Seller should deliver the goods in 60 days after receiving the deposit.</p>
        <p><span>7. 装运港Port of loading: </span>
          <el-input placeholder="请输入相关内容" :readonly="!editable" v-model="data.bf_portOfLoad"></el-input>
        </p>
        <p><span>8. 目的港Port of Loading: </span>
          <el-input placeholder="请输入相关内容" :readonly="!editable" v-model="data.bf_portOfDestination"></el-input>
        </p>
        <p><span>9. 运输Shipment	: </span>
          <el-input placeholder="请输入相关内容" :readonly="!editable" v-model="data.bf_shipment"></el-input>
        </p>
        <p>买方负责运输的情况下，货物发运前，必须将货代公司联系人信息邮件告知卖方；卖方应协助买方将合同货物从装货港运到目的港。 允许分批，允许转运。 The buyer is reponsiable for the transpotation, the cargo agent contact information must be sent to the seller before shipment. The Sellers shall provide the necessary assistance.
          Transshipment is allowed. Partial shipment is allowed.
        </p>
        <p><span>10. 最迟装期Latest Shipment Date		As per buyer's request</span></p>
        <p><span>11. 保险Insurance</span></p>
        <p>不含中国国内运输及国际海运保险 Without China domesitc transportation insurance and Insurance of the shipment by sea；</p>
        <p><span>12. 付款方式Payment Term:</span></p>
        <p>12.1 合同订金Contract Deposit <span class="special-12">{{this.bf_depositMoney}}</span></p>
        <p>买方应自合同签订之日起2周内支付
          <el-input placeholder="请输入相关内容" @input="mustUpdate" :readonly="!editable" v-model="data.bf_downPaymentRate"></el-input> 订金折合美元
          <el-input placeholder="请输入相关内容" @input="mustUpdate" :readonly="!editable" v-model="data.bf_downPayment"></el-input>。 订金收取后，如因买方的任何原因不能继续执行合同，卖方不予退还，除非卖方的供应商做了相应退款。
          The buyer shall pay the <span class="color-red">{{data.bf_downPaymentRate}}</span>deposit by USD <span class="color-red">{{data.bf_downPayment}}</span> within 2 weeks from the date of
          contract signed. If the deal cannot be continued for any reason by the buyer, the seller will not refund the deposit unless the seller's supplier has made the refund in advance.</p>
        <p>12.2 合同尾款Balance Payment <span class="special-12">{{this.bf_balanceMoney}}</span></p>
        <p>买方必须根据卖方出具的《付款通知单》上的载明日期起90天内付清剩余货款，如逾期支付，应自逾期日起按未还余额的0.5%/天计收罚金, 并且卖方有权调整授予买方的赊销额度，甚至取消合作额度。
        </p>
        <p>
          The buyer shall pay the balance by USD XXX within 90 days strarted from the day appointed by 《Payment Advice》. If the payment is overdue,based on outstanding balance,buyer should pay the fine by interest 0.5% per day. And seller can reserve the rights
          to adjust the cooperation mode or even cacel the credit limit of open account.</p>
        <p>12.3 卖方收款账户信息 Beneficiary Payment Route</p>
        <p><span>收款人Beneficiary：</span> TIAN JIN FINANCIAL TRADE LINK IMPORT AND EXPORT CO.,LTD</p>
        <p><span>收款账号Account No.: </span> 1000000010120100506972</p>
        <p><span>收款人地址Address:</span> NO.88-2-2205,HUANHE SOUTH ROAD,CHINA(TIANJIN)PILOT FREE TRADE ZONE TIANJIN AIRPORT ECONOMIC AREA),TIANJIN,CHINA</p>
        <p><span>收款银行Bank：</span> CHINA ZHESHANG BANK BEIJING BRANCH</p>
        <p><span>银行地址Bank address:</span> NO.1 FINANCIAL STEREET,XICHENG DISTRICT,BEIJING,CHINA</p>
        <p><span>银行代码SWIFT CODE:</span> ZJCBCN2N</p>
        <p>备注：买方付款时需要注明销售合同号、发票号和付款内容。</p>
        <p>Remark: The Buyer must indicate the sales contract number, invoice number and payment purpose (e.g. deposit/prepayment/balance payment, etc.) in the bank slip. Remark: stipulated by this Contract. Meanwhile, the Buyer must indicate the sales contract
          number, invoice number and payment purpose (e.g. deposit/repayment/logistics fee/interests, etc.) in the bank slip. invoice number and payment purpose (e.g. deposit/repayment/logistics fee/interests, etc.) in the bank slip.</p>
        <p><span>13. 单据要求Documents</span></p>
        <div class="fapiao">
        <p>(1)
          <el-select :disabled="!editable" @change="mustUpdate" v-model="data.bf_commercialInvoice">
            <el-option :label="bf_symbol[0]" value="1"></el-option>
            <el-option :label="bf_symbol[1]" value="0"></el-option>
          </el-select> 商业发票 
          <input type="number" v-model="bf_commercialInvoice_num" @input="ctrlInputNumber('bf_commercialInvoice_num', $event)">  份 Commercial Invoice in 
          <input type="number" v-model="bf_commercialInvoice_copy_num" @input="ctrlInputNumber('bf_commercialInvoice_copy_num', $event)"> copies 
        <p>
        <p>(2)
          <el-select :disabled="!editable" @change="mustUpdate" v-model="data.bf_fullForm">
            <el-option :label="bf_symbol[0]" value="1"></el-option>
            <el-option :label="bf_symbol[1]" value="0"></el-option>
          </el-select> 全套提单 Full set of Bills of Lading</p>
        <p>(3)
          <el-select :disabled="!editable" @change="mustUpdate" v-model="data.bf_airParcel">
            <el-option :label="bf_symbol[0]" value="1"></el-option>
            <el-option :label="bf_symbol[1]" value="0"></el-option>
          </el-select> 空运单 Air Waybills</p>
        <p>(4)
          <el-select :disabled="!editable" @change="mustUpdate" v-model="data.bf_fullInsurance">
            <el-option :label="bf_symbol[0]" value="1"></el-option>
            <el-option :label="bf_symbol[1]" value="0"></el-option>
          </el-select> 全套保险单据 Full set of Insurance Policy /Certificate in 
          <input  type="number" v-model="bf_fullInsurance_num"  @input="ctrlInputNumber('bf_fullInsurance_num', $event)"> copies</p>
        <p>(5)
          <el-select :disabled="!editable" @change="mustUpdate" v-model="data.bf_packageList">
            <el-option :label="bf_symbol[0]" value="1"></el-option>
            <el-option :label="bf_symbol[1]" value="0"></el-option>
          </el-select> 装箱单 
          <input type="number" v-model="bf_packageList_num"  @input="ctrlInputNumber('bf_packageList_num', $event)" >
          份 Packing List in 
          <input type="number" v-model="bf_packageList_copy_num"   @input="ctrlInputNumber('bf_packageList_copy_num', $event)">　copies</p>
        <p>(6)
          <el-select :disabled="!editable" @change="mustUpdate" v-model="data.bf_originCertificate">
            <el-option :label="bf_symbol[0]" value="1"></el-option>
            <el-option :label="bf_symbol[1]" value="0"></el-option>
          </el-select> 原产地证 
          <input type="number"  v-model="bf_originCertificate_num" @input="ctrlInputNumber('bf_originCertificate_num', $event)" >
          份Certificate of Origin in　
          <input type="number"  v-model="bf_originCertificate_copy_num" @input="ctrlInputNumber('bf_originCertificate_copy_num', $event)">　 copies</p>
        </div>
        <p><span>14. 产品质量Quality：</span></p>
        <p>所有货物出运前都必须通过买方检验，买方可以派代表或代理人或任何第三方检验机构对产品质量进行检验。 检验合格的，须出具书面的《质量确认函》, 现场出具书面意见有困难的，必须邮件确认。 卖方在收到《质量确认函》后协助买方指定的货代发货。
        </p>
        <p>
          Whatever buyer designate its representative or agent or any third inspection organization, The goods quality must be inspected before shipment. After inspection, the buyer must issue the 《Quality Confirmation Letter》 or do the same work by Email. The
          seller will do not the shipment until receiving the《Quality Confirmation Letter》.</p>
        <p><span>15. 合同不可抗力 FORCE MAJEURE</span></p>
        <p>
          对于制造或装船运输过程中可能产生的不可抗力而造成的迟交货或不能交货，卖方可以不承担责任。 卖方应立即在不可抗力产生的十四日内将有关情况通知买方。在此情况下，卖方仍应尽最大努力采取各种措施促使货物的发运。 如果事故持续十周，买方有权取消合同。
        </p>
        <p>
          The Sellers shall not be held responsible for the delay in shipment or non-delivery of the goods due to Force Majeure, which might occur during the process of manufacturing or in the course of loading or transit. The Sellers shall advise the Buyers immediately
          of the occurrence mentioned above and within fourteen days thereafter, Under such circumstances the Sellers, however, are still under the obligation to take all necessary measures to hasten the delivery of the goods. In case the accident lasts
          for more than 10 weeks, the Buyers shall have the right to cancel the contract.</p>
        <p><span>16. 仲裁 ARBITRATION</span></p>
        <div>
          <p>与此合同有关的争议应通过友好协商解决,如果协商无法解决，提交中国国际经济贸易仲裁委员会进行仲裁。 按照申请仲裁时该会现行有效的仲裁规则进行仲裁 。仲裁裁决是终局的，对双方均有约束力。仲裁费用由败诉方承担
          </p>
          <p>
            Any dispute arising from or in connection with this Contract shall be submitted to China International Economic and Trade Arbitration Commission for arbitration which shall be conducted in accordance with the Commission's arbitration rules in effect at
            the time of applying for arbitration. The arbitral award is final and binding upon both parties. Arbitration fee shall be borne by the losing party.</p>
        </div>
        <p><span>17. 银行费用BANK CHARGES</span></p>
        <div>
          <p>买方应保证卖方按合同净额收款，银行费用由买方承担。</p>
          <p>
            The buyer shall ensure the seller to get all the contract payment wihtout any deduction, and the bank charges shall be borne by the buyer
          </p>
        </div>
        <p><span>18. 其他条款Other</span></p>

        <div>
          <p>本合同以英文版为准,一式贰份，卖买双方各执壹份</p>
          <p>In this contract,the English version shall prevail.</p>
          <p>This contract signed in two copies,each party holds one copy only.</p>
        </div>

        <div>
          <el-row>
            <el-col :span="10">
              买方Buyer：
            </el-col>
            <el-col :span="10">
              卖方 Seller:
            </el-col>
          </el-row>

          <el-row>
            
            <el-col :span="10"> &nbsp;{{this.data.bf_buy_name}}</el-col>
            <el-col :span="14">TIAN JIN FINANCIAL TRADE LINK IMPORT AND EXPORT CO.,LTD </el-col>
          </el-row>

          <el-row>
            <el-col :span="10">
              代表签字Representative Signature:
            </el-col>

            <el-col :span="10">
              代表签字Representative Signature:
            </el-col>
          </el-row>
        </div>



      </div>
    </div>

  </div>


  <div class="upload">
    <p class="upload-hint">票据/附件</p>
    <div>
      <div class="upload-btn">
        <input type="file"  v-show="editable"  name="file" multiple @change="selectFiles">
        <el-button :disabled="!editable" type="primary">选择附件</el-button>
      </div>

      <ul class="upload-files">
        <li @mouseover="handleOver(item)"  :key="index" @mouseout="handleOut(item)" v-for="(item,index) in data.attachedFiles">
          <span @click="download(item.id, $event)">{{item.name}}</span>
          <span v-if="editable && item.status" class="el-icon-circle-check" style="color:#67c23a;"></span>
          <span v-else-if="editable" class="el-icon-circle-close" @click="changeFiles(index,item)" style="color:red;"></span>
        </li>
      </ul>
    </div>
  </div>
</div>
</template>

<script>
import {
  uploadFiles,
  getBusinessMesg
} from '@/server/initiatingprocess';

import {filedownload , deleteFile} from '@/server/customermanagement/index.js';
import {englishmoney, toFixed} from '@/util/transform';


export default {
  created() {
    let _this = this;
    this.bf_orderDate = this.data.bf_orderDate;

    this.data.relatedChangedStatusPI = 0;
    this.data.relatedChangedStatusDO = 0;

    this.relatedPropPI.forEach (e => {
      _this.oldRelatedValuePI[e] = _.cloneDeep(_this.data[e]);
      _this.newRelatedValuePI[e] = _.cloneDeep(_this.data[e]);
    });

    this.oldRelatedValueDO = _.cloneDeep(this.data.bf_table1);
    this.newRelatedValueDO = _.cloneDeep(this.data.bf_table1);

    this.oldRelatedValuePR = _.cloneDeep((this.data.bf_table1[this.data.bf_table1.length - 2].bf_table1_lineAmount).toString().slice(3));
    this.newRelatedValuePR = _.cloneDeep((this.data.bf_table1[this.data.bf_table1.length - 2].bf_table1_lineAmount).toString().slice(3));

    getBusinessMesg({
      type: 1
    }).then((response) => {
      this.businessMesg = response.data.datas;

      this.bf_buy_nameOptions = [];

      this.businessMesg.forEach(e => {
        this.bf_buy_nameOptions.push(e.customerName);
      });
    });

  },

   mounted(){
  },
  updated() {
    let _this = this;
    this.bf_orderDate = this.data.bf_orderDate;
    
    if (this.isUpdateAmount){
      this.isUpdateAmount = false;
      this.updateAmount();
    } else {
      this.updateTable();
    }

    this.currencyValue = this.data.bf_currencyValue;

    if (this.fromOther){
      this.bf_commercialInvoice_num =  this.data.bf_commercialInvoice_num;
      this.bf_commercialInvoice_copy_num = this.data.bf_commercialInvoice_copy_num;
      this.bf_fullInsurance_num = this.data.bf_fullInsurance_num;
      this.bf_packageList_num = this.data.bf_packageList_num;
      this.bf_packageList_copy_num = this.data.bf_packageList_copy_num;
      this.bf_originCertificate_num = this.data.bf_originCertificate_num;
      this.bf_originCertificate_copy_num = this.data.bf_originCertificate_copy_num;

      this.bf_depositMoney =  this.data.bf_depositMoney;
      this.bf_balanceMoney =  this.data.bf_balanceMoney;
    }

    if (this.clickTimes == 1 && (!this.fromOther)) {
      this.clickTimes++;

      let current = this.data.bf_table1, relatedData = this.relatedData1.bb_table1;

      current.splice(relatedData.length + 2);

      if (!this.fromOther) {
        for (let i = 0; i < 3; i++){
         for (let prop in current[i]) {
            current[i][prop] = '';
          } 
        }
      }
      
      for (let i = 0; i < relatedData.length + 2; i++)  {

         if (!current[i]){
           current.push({
             bf_table1_product: '',
             bf_table1_description: '',
             bf_table1_price: '',
             bf_table1_lineAmount: '',
             bf_table1_quantity: ''
           });
         } else {
          //  for (let prop in current[i]) {
          //    current[i][prop] = '';
          //  }
         }
      }


      for (let i = 0; i < relatedData.length; i++)  {
        current[i].bf_table1_product = relatedData[i].bb_productName;
      }
    }

    if (this.clickTimes == 1  && this.fromOther) {

      this.clickTimes++;
    }

    this.relatedPropPI.forEach (e => {
      _this.newRelatedValuePI[e] = _.cloneDeep(_this.data[e]);
    });

    if (!_.isEqual(this.oldRelated, this.newRelatedValuePI)){
      this.data.relatedChangedStatusPI = 1;
      this.oldRelated = _.cloneDeep(this.newRelatedValuePI);
    }


    this.newRelatedValueDO = _.cloneDeep(this.data.bf_table1);

    if (!_.isEqual(this.newRelatedValueDO, this.oldRelatedValueDO)) {
      this.data.relatedChangedStatusDO = 1;
      this.oldRelatedValueDO = _.cloneDeep(this.newRelatedValueDO);
    }

    this.newRelatedValuePR = _.cloneDeep((this.data.bf_table1[this.data.bf_table1.length - 2].bf_table1_lineAmount).slice(3));
    if (!_.isEqual(this.newRelatedValuePR, this.oldRelatedValuePR)) {
      this.data.relatedChangedStatusPR = 1;
      this.oldRelatedValuePR = _.cloneDeep(this.newRelatedValuePR);
    }
  },
  methods: {
    indexMethod(value) {
      let lines = this.data.bf_table1.length;
      if (lines - 2 === value) {
        return '合计Total';
      } else if (lines - 1 === value) {
        return 'SAY Total';
      }
      return value + 1;
    },


    selectFiles(event) {
      // this.data.attachedFiles.splice(0);
      let _this = this;


      //直接上传，并且获得后端返回的文件的url,将url保存到 this.data.attachedFiles中
      uploadFiles(event.target.files).then((resArr) => {
        resArr.forEach(function(res, i) {
          _this.data.attachedFiles.push({
            name: event.target.files[i].name,
            status: 1,
            id: res.data.datas[0].id
          });
        });

        _this.$forceUpdate();
      });
    },
    changeFiles(index,item) {
      deleteFile({'id':item.id}).then((res) => {
        if(res.code != 1 ){
          this.$message.error('删除失败，请检查网络后重试');
        } else {
          this.data.attachedFiles.splice(index, 1);
        }
      });
    },
    handleOver(item){
      item.status = 0;
      this.$forceUpdate();
    },
    handleOut(item){
      item.status = 1;
      this.$forceUpdate();
    },
    download(id, event){
      window.open('http://47.104.93.41/api/common/download?id='+id);
    },
    addNewLine(currentIndex, table, event) {

      this.specialClick = true;
      let newLine = _.cloneDeep(table[currentIndex]);

      // for (let prop in newLine) {
      //   newLine[prop] = '';
      // }

      table.splice(currentIndex + 1, 0, newLine);
      this.handleTableNumberChange();
      this.$forceUpdate();
    },
    removeCurrentLine(currentIndex, table, event) {

      this.specialClick = true;
      if (table.length > 3) {
        table.splice(currentIndex, 1);
      }
      this.handleTableNumberChange();
      this.$forceUpdate();
    },
    spanMethod({
      row,
      column,
      rowIndex,
      columnIndex
    }) {
      let lines = this.data.bf_table1.length;

      if (lines - 2 === rowIndex) {
        if (0 === columnIndex) {
          return [1, 3];
        } else if (1 === columnIndex || 2 === columnIndex || 4 === columnIndex || 6 == columnIndex) {
          return [0, 0];
        } else if (3 === columnIndex || 5 == columnIndex) {
          return [1, 2];
        }
      } else if (lines - 1 === rowIndex) {
        if (0 === columnIndex) {
          return [1, 3];
        } else if (1 === columnIndex || 2 === columnIndex ||
          3 === columnIndex || 4 === columnIndex || 6 === columnIndex) {
          return [0, 0];
        } else if (5 === columnIndex) {
          return [1, 4];
        }
      }
    },
    clickEditTableCell(row, column, cell, event) {
      if (row){
        this.clickTableIndex = row.customIndex;
      }

      if (this.tableChanged) {
        this.updateTable();
        this.$forceUpdate();
        this.tableChanged = false;
      }

    },

    handleTableNumberChange(value) {

      if (!this.specialClick) {
        this.tableChanged = true;
        this.clickEditTableCell();
      } else {
        this.tableChanged = false;
        this.specialClick = false;

        let current = this.data.bf_table1, lines = current.length;
        for (let i = 0; i < lines - 2; i++) {
          current[i].customIndex = i;
        }
      }
    },
    handleTableNumberChange2(value) {
      this.isUpdateAmount = true;
      this.updateAmount();
      this.$forceUpdate();
    },
    updateAmount(){
      let current = this.data.bf_table1, amounts = 0, lines = current.length;

      for (let i = 0; i < lines - 2; i++) {
        current[i].bf_table1_lineAmount = toFixed(current[i].bf_table1_lineAmount, 2);
        amounts += parseFloat(current[i].bf_table1_lineAmount);
      }

      amounts = toFixed(amounts, 2);

      current[lines - 2].bf_table1_lineAmount = "US$" + amounts.toString().replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
      current[lines - 1].bf_table1_lineAmount = englishmoney(amounts) + '';
    },
    updateTable() {
 
      let quantitys = 0, amounts = 0;
      let current = this.data.bf_table1, lines = current.length;
      let correctValue = 0;


      for (let i = 0; i < lines - 2; i++) {

        current[i].bf_table1_quantity  = parseInt(current[i].bf_table1_quantity);
        current[i].bf_table1_price = toFixed(current[i].bf_table1_price, 2);


        correctValue = (current[i].bf_table1_quantity * current[i].bf_table1_price).toFixed(2);

        /*********/
        if (current[i].bf_table1_lineAmount && (current[i].bf_table1_lineAmount != correctValue)) {
        } else {
          current[i].bf_table1_lineAmount = toFixed(correctValue, 2);
        }
        /*********/


         if (i == this.clickTableIndex){
           current[i].bf_table1_lineAmount = toFixed(correctValue, 2);
         }

        quantitys += current[i].bf_table1_quantity;
        amounts += parseFloat(current[i].bf_table1_lineAmount);

        // current[i].customIndex = i;
      }

      current[lines - 2].bf_table1_quantity = quantitys + '';
      amounts = toFixed(amounts, 2);
      current[lines - 2].bf_table1_lineAmount = "US$" + amounts.toString().replace(/(\d)(?=(\d{3})+\.)/g, '$1,');

      current[lines - 1].bf_table1_lineAmount = englishmoney(amounts) + '';

      current[lines - 1].specialColumn = true;
      current[lines - 2].specialColumn = true;
    },
    selBuyer(value) {

      let now = new Date();
      let m = now.getMonth() + 1;
      let d = now.getDate();
      m = m < 10 ? '0' + m : m;
      d = d < 10 ? '0' + d : d;


      let currentSel = this.businessMesg.find(e => {
        return e.customerName == value;
      });

      this.data.bf_buy_address = currentSel.customerAddress;
      this.data.bf_buy_tel = currentSel.customerPhone;
      this.data.bf_buy_fax = currentSel.customerFax;
      this.data.bf_buy_email = currentSel.customerEmail;
      this.data.bf_orderNumber = currentSel.customerAbbreviation + now.getFullYear() + m + d + _.random(100, 999);
      this.$forceUpdate();
    },
    mustUpdate() {
      this.$forceUpdate();
    },
    mustUpdate2() {
      this.data.bf_orderDate = this.bf_orderDate;
      this.$forceUpdate();
    },

    /**选择币种 */
    currencySel(name){


       

        return (h, {column, $index}) => {
    
        let self = this;
        var selAttr = {};
        if (!this.editable){
         selAttr.disabled = 'disabled';
         }

        return  h("div", {
          attrs: {
            class: "select-currency"
          }
        }, [
          h("span", name),
          h("select", {
            attrs: {...selAttr},
            domProps: {
             value: self.currencyValue
            },
          on: {
            change: function(event){
              self.currencyValue = event.target.value;
              self.data.bf_currencyValue = event.target.value;
            }
          }
          },[
            h("option", "人民币"),
            h("option", "美元"),
            h("option", "加元"),
            h("option", "欧元"),
          ])
        ]);
      }
    },
    currentSelEN(name){
      return (h, {column, $index}) => {
        let temp;
        switch (this.currencyValue){
          case '人民币':
          temp = 'RMB';
          break;
          case '美元':
          temp = 'USD';
          break;
          case '欧元':
          temp = 'EUR';
          break;
          case '加元':
          temp = 'CAD';
          break;
        }
        return h('div',null, `${name}(${temp})`);
      }
    },
    //输入整数校验
    ctrlInputNumber(attr, event){
      this[attr] = parseInt(event.target.value);
      this.data[attr] = this[attr];
    },

    //定金，尾款
    handleExtraMoney(name, event){
      this[name] = event.target.value;
      this.data[name] = event.target.value;
    }
  },
  computed: {
    tableData() {

      let quantitys = 0, amounts = 0;
      let current = this.data.bf_table1, lines = current.length;
      let correctValue = 0;

      for (let i = 0; i < lines - 2; i++) {

        correctValue = (current[i].bf_table1_quantity * current[i].bf_table1_price).toFixed(3);

        /*********/
        if (current[i].bf_table1_lineAmount && (current[i].bf_table1_lineAmount != correctValue)) {
        } else {
          current[i].bf_table1_lineAmount = toFixed(correctValue, 2);
        }
        /*********/

        quantitys += current[i].bf_table1_quantity;
        amounts += parseFloat(current[i].bf_table1_lineAmount);

        current[i].customIndex = i;
      }

      amounts = toFixed(amounts, 2);

      current[lines - 2].bf_table1_quantity = quantitys + '';
      current[lines - 2].bf_table1_lineAmount = "US$" + amounts.toString().replace(/(\d)(?=(\d{3})+\.)/g, '$1,');

      current[lines - 1].bf_table1_lineAmount = englishmoney(amounts) + '';

      current[lines - 1].specialColumn = true;
      current[lines - 2].specialColumn = true;

      return current;
    }
  },
  props: {
    businessformNO: {
      type: String,
      required: true
    },
    data: {
      type: Object,
      required: true
    },
    relatedData1: {
      type: Object,
      required: true
    },
    editable: {
      type: Boolean,
      required: true
    },
    fromOther: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      clickTableIndex: -1,
      clickTimes: 0,
      tableChanged: false,
      specialClick: false,
      fireClick: false,
      isUpdateAmount: false,
      bf_symbol: [
        '√', '×'
      ],
      bf_orderDate: '',
      businessMesg: [],
      bf_buy_nameOptions: ['xxx', 'yyy'],
      oldRelatedValuePI: {},
      newRelatedValuePI: {},
      relatedPropPI: [
        "bf_buy_name",
        "bf_orderNumber",
        "bf_buy_address",
        "bf_orderDate",
        "bf_tradeTerm",
        "bf_portOfLoad",
        "bf_portOfDestination",
        "bf_table1"
      ],
      oldRelatedValueDO: {},
      newRelatedValueDO: {},
      oldRelatedValuePR: 0,
      newRelatedValuePR: 0,
      currencyValue: '人民币',
      bf_commercialInvoice_num: '0',
      bf_commercialInvoice_copy_num: '0',
      bf_fullInsurance_num: '0',
      bf_packageList_num: '0',
      bf_packageList_copy_num: '0',
      bf_originCertificate_num: '0',
      bf_originCertificate_copy_num: '0',
      bf_balanceMoney: 0,
      bf_depositMoney: 0
    }
  }
}
</script>

<style lang="scss">
.foreigntradecontract {
    padding: 20px;
    border: 1px solid #999;
    font-size: 15px;
    line-height: 30px;

    p {
      padding: 5px 0;
    }

    .export {
        float: right;
    }

    .head {
        h2 {
            text-align: center;
        }

        .head-ctrl {
            height: 60px;
            .order-number {
                padding: 16px 0;
                float: left;
            }
            button {
                float: right;
            }
        }
    }

    .head-1 {
        text-align: center;
        padding: 20px;

    }

    .select-currency {
      select {
        margin-left: 12px;
        height: 30px;
        width: 60px;
      }
    }

    .contract {
        > h1 {
            text-align: center;
        }

        .contract-1 {
            padding: 20px;
            .el-select {
                width: 100%;
            }

            .el-form-item__label {
                width: 120px;
            }
            p {
                > span {
                    font-weight: bolder;
                    padding-right: 20px;
                }
            }
        }

        .contract-order {
            float: right;
        }

        .contract-table {
            padding: 20px;

            .contract-table-2 {
            }

            .el-table__body-wrapper {
                overflow: hidden;
             }

            td {
                border: 1px solid #e6ebf5;
            }

            .el-table thead.is-group th {
                background: #e6e6e6;
            }

            .el-table--border td,
            .el-table--border th {
                border: 1px solid #e6ebf5;
            }

            .special {

                .el-input {
                  .el-input__inner {
                  border: none !important;
                  }
                }

                .color-red {
                    color: red;
                    padding: 0 3px;
                }
                .el-input {
                    width: 300px;
                }

                p {
                    > span {
                        font-weight: bolder;
                    }
                }

                .el-select {
                    width: 100px;
                    .el-input__inner {
                        width: 100px;
                    }
                    .el-input__suffix {
                        right: 201px;
                    }


                }

                span.special-12 {
                  font-weight: normal;
                  margin-left: 30px;
                }
            }

            .cell-edit-input {
                .el-input__inner {
                    border: none;
                    background: transparent;
                    padding: 0;
                    text-align: center;
                }

                .el-input-number__decrease,
                .el-input-number__increase {
                    width: 20px;

                    border: none;
                    background: transparent;
                }

                .el-input-number {
                    width: 100%;
                    min-width: 100px;
                }
            }
        }


        .extra-table {
          .extra-money {
            border: 1px solid #e6ebf5;
            text-align: center;
            color: #5a5e66;

            &:nth-child(1){
              border-top: none;
            }

            .el-col:nth-child(2){
              border-left: 1px solid #e6ebf5;
              border-right: 1px solid #e6ebf5;
            }

            input {
              width: 90%;
              border: none;
              outline: none;
              text-indent: 1em;
              color: #5a5e66;
            }
          }
        }

        .fapiao {
            .el-input-number {
                 width: 90px;
            }
            .el-input {
               width: 100% !important;
            }

            .el-select .el-input__suffix {
                right: 10px !important;
            }

            input {
              width: 80px;
              border: none;
            }
        }
    }

    .upload {
        > div {
            border: 1px solid #999;
            padding: 20px 0 40px 20px;
        }

        .upload-btn {
            position: relative;
            > input {
                opacity: 0;
                width: 100px;
                height: 40px;
                position: absolute;
                top: 0;
                left: 0;
            }
        }

        .upload-files {

            > li {
                width: 300px;
                padding: 10px 0;
                transition: all 0.5s linear;

                &:hover {

                  >span {
                    color: #409EFF;
                  }
                }
              }

            font-size: 16px;
            span {
                padding: 0 10px;
                cursor: pointer;
            }
            span.el-icon-close:hover {
                cursor: pointer;
            }
        }
        .upload-hint {
            font-size: 20px;
            margin-bottom: 10px;
        }
    }

}
</style>
